<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Canvas 画图工具</title>
  </head>
  <body>
    <canvas
      id="drawing-board"
      width="800"
      height="600"
      style="border: 1px solid #000000"
    ></canvas>
    <script>
      document.addEventListener("DOMContentLoaded", function () {
        const canvas = document.getElementById("drawing-board");
        const ctx = canvas.getContext("2d");

        let painting = false;

        function startPosition(e) {
          painting = true;
          draw(e);
        }

        function finishedPosition() {
          painting = false;
          ctx.beginPath();
        }

        function draw(e) {
          if (!painting) return;
          ctx.lineWidth = 5;
          ctx.lineCap = "round";
          ctx.strokeStyle = "#000000";

          ctx.lineTo(
            e.clientX - canvas.offsetLeft,
            e.clientY - canvas.offsetTop
          );
          ctx.stroke();
          ctx.beginPath();
          ctx.moveTo(
            e.clientX - canvas.offsetLeft,
            e.clientY - canvas.offsetTop
          );
        }

        canvas.addEventListener("mousedown", startPosition(e));
        canvas.addEventListener("mousemove", draw(e));
        canvas.addEventListener("mouseup", finishedPosition());
        canvas.addEventListener("mouseout", finishedPosition());
      });
    </script>
  </body>
</html>
